<template>
  <section id="app" class="todoapp">
    <header class="header">
      <h1>todos</h1>
      <input
        class="new-todo"
        placeholder="What needs to be done?"
        autocomplete="off"
        autofocus
        v-model="input"
        @keyup.enter="addTodo"
        >
    </header>
    <section class="main" v-show="count">
      <ul class="todo-list">
        <input id="toggle-all" v-model="allDone" class="toggle-all" type="checkbox">
        <label for="toggle-all">Mark all as complete</label>
          <li v-for="todo of filterTodos"
          :key="todo"
          :class="{editing: todo === editingToDo, completed: todo.completed}">
            <div class="view">
           <input class="toggle" type="checkbox" v-model="todo.completed" />
             <label @click="changeCheckStaut(todo)" @dblclick="editTodo(todo)">{{ todo.text }}</label>
            <button class="destroy" @click="remove(todo)" ></button>
          </div>
          <input
            class="edit"
            type="text"
            v-editing-focus="todo === editingToDo"
            v-model="todo.text"
            @keyup.enter="doneEdit(todo)"
            @blur="doneEdit(todo)"
            @keyup.esc="cancelEdit(todo)"
            >
          </li>

      </ul>  
     </section> 
    <footer class="footer" v-show="count">
      <span class="todo-count">
        <strong>{{remainTodoCount}}</strong> {{ remainTodoCount > 1 ? 'items': 'item' }} left
      </span>
      <ul class="filters">
        <li><a href="#/all">All</a></li>
        <li><a href="#/active">Active</a></li>
        <li><a href="#/completed">Completed</a></li>
      </ul>
       <button class="clear-completed" @click="removeCompleted" v-show="count > remainTodoCount">
         Clean completed
       </button>
    </footer>
  
  </section>
</template>

<script>
import { computed, onMounted, onUnmounted, ref, watchEffect } from 'vue'
import useLocalStorage from './utils/localstorage'
import './assets/index.css'
const storage = useLocalStorage()
 // 1. 添加待办事件
const useAdd = todos => {
    //  ref 返回一个响应式的对象
    const input = ref('') 
    // 文本框中输入的值添加到待办列表中
    const addTodo = () => {
      // 输入空格，直接返回
      const text = input.value && input.value.trim()
      if (text.length === 0) return 
      // 将输入的待办事件，添加到第一个
      todos.value.unshift({
        text,
        completed: false
      })
      input.value = ''
    }
    return {
      input,
      addTodo
    }
  
}
// 2. 删除待办事件
const useRemove = todos => {
  const remove = todo => {
    // 获取todo的索引
    let index = todos.value.indexOf(todo)
    todos.value.splice(index, 1)
  }
  // 删除已经完成的事项
  const removeCompleted = () => {
    todos.value = todos.value.filter(todo => !todo.completed)
  }
  return {
    remove,
    removeCompleted
  }
}
// 3. 编辑待办项
const useEdit = remove => {
                                                                                                               
  // 记录原有的数据
  let beforEditText = ''
  // 标识编辑的状态
  const editingToDo = ref(null)
  // 开始编辑，需要记录编辑之前的文本数据
  const editTodo = todo => {
    beforEditText = todo.text
    editingToDo.value = todo
  }
  // 完成编辑
  const doneEdit = todo => {
    if (!editingToDo.value) return

    todo.text = todo.text.trim()
    // 如果文本框的值为空，则删除这一项
    todo.text || remove(todo)
    // 取消状态状态
    editingToDo.value = null
  }
  // 取消编辑
  const cancelEdit = todo => {
    // 取消状态状态
    editingToDo.value = null
    // 恢复文本数据
    todo.text = beforEditText
  } 
  return {
    editingToDo,
    editTodo,
    doneEdit,
    cancelEdit
  }
}
// 4. 切换待办事项的状态
const useFilter = todos => {
  const allDone = computed({
    get () {
      // 所有事项都已完成的，返回true
      return !todos.value.filter(todo => !todo.completed).length
    },
    set (value) {
      todos.value.forEach(todo => {
        todo.completed = value
      })
    }
  })
  const changeCheckStaut = todo => {
    todo.completed =  !todo.completed
  }
  // 定义一个对象用于存放获取all, active, completed三种不同状态的事项方法
  const filter = {
    all: list => list,
    active: list => list.filter(item => !item.completed),
    completed: list => list.filter(item => item.completed)
  }
  // 定义一个存放当前状态的响应对象，默认“显示全部”
  const type = ref('all')
  // 计算属性依赖type , 调用filter对象中对应的处理函数
  const filterTodos = computed(() => filter[type.value](todos.value))
  // 未完成的事项个数
  const remainTodoCount = computed(() => filter.active(todos.value).length)
  // 记录待办事项总个数
  const count = computed(() => todos.value.length)
  // 定义一个用于处理hash 变化的处理函数
  const onHashChange = () => {
    // 获取hash 值
    const hash = window.location.hash.replace('#/', '')
    if (filter[hash]) {
       type.value = hash
    }

  }
  onMounted (() => {
    window.addEventListener('hashchange', onHashChange)
    onHashChange()
  }) 
  onUnmounted (() => {
    window.removeEventListener('hashchange', onHashChange)
  })
  return {
    allDone,
    changeCheckStaut,
    filterTodos,
    remainTodoCount,
    count
  }
}
// 5. localstorage存储待办事项
const useStorage = () => {
  const KEY = 'TODOSKEY'
  const todos = ref(storage.getItem(KEY) || [])
  // 待办事项列表一发生改变就触发set
  watchEffect (() => storage.setItem(KEY, todos.value))
  return todos
}
export default {
  name: 'App',
  setup () {
    const todos = useStorage()
    const { remove, removeCompleted } = useRemove(todos)
    return {
     // 这个对象中的数据供模板使用
     todos,
     remove,
     removeCompleted,
     ...useAdd(todos),
     ...useEdit(remove),
     ...useFilter(todos)
    }
  },
  directives: {
    editingFocus: (el, binding) => {
      binding.value && el.focus()
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 160px;
}
</style>
